<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑合同"
    width="80%"
    :destroy-on-close="false"
    :close-on-click-modal="false"
  >
    <form-create
      v-model="formData"
      v-model:api="fapi"
      :rule="rule"
      :option="option"
      @submit="onSubmit"
    />
    
    <template #footer>
      <div class="dialog-footer">
        <el-upload
          class="upload-demo"
          :auto-upload="false"
          accept=".md"
          :show-file-list="false"
          :on-change="handleFileChange"
        >
          <el-button type="primary">
            <Icon icon="ep:upload" class="mr-5px" /> 导入Markdown
          </el-button>
        </el-upload>
        
        <el-button @click="copyContent" type="info">
          <Icon icon="ep:document-copy" class="mr-5px" /> 复制内容
        </el-button>
        
        <el-button @click="exportMarkdown" type="primary">
          <Icon icon="ep:download" class="mr-5px" /> 导出Markdown
        </el-button>
        <el-button @click="exportWord" type="primary">
          <Icon icon="ep:document" class="mr-5px" /> 导出Word
        </el-button>
        <el-button @click="exportPDF" type="success">
          <Icon icon="ep:document" class="mr-5px" /> 导出PDF
        </el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import formCreate from "@form-create/element-ui"
import download from '@/utils/download'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import html2pdf from 'html2pdf.js'
import { marked } from 'marked'
import TurndownService from 'turndown'

defineOptions({ name: 'ContractEditor' })

const dialogVisible = ref(false)
const option = ref(formCreate.parseJson('{"form":{"inline":false,"hideRequiredAsterisk":false,"labelPosition":"right","size":"default","labelWidth":"100px"},"language":{},"resetBtn":{"show":false,"innerText":"重置"},"submitBtn":{"show":false,"innerText":"提交"}}'))
const rule = ref(formCreate.parseJson('[{"type":"Editor","field":"836c38a8-b68d-4525-99b0-c4d6ff25ce29","title":"","info":"","$required":false,"_fc_id":"id_Fco1m8401djvabc","name":"ref_Fh5am8401djvacc","display":true,"hidden":false,"_fc_drag_tag":"Editor","value":"<p><br></p>"}]'))
const fapi = ref(null)
const formData = ref({})
const contractName = ref('合同文档')

const emit = defineEmits(['success'])

const onSubmit = () => {
  dialogVisible.value = false
  ElMessage.success('合同编辑演示完成')
}

/** 打开弹窗 */
const open = (contractId?: number) => {
  dialogVisible.value = true
  if (contractId) {
    console.log('加载合同ID:', contractId)
  }
}

/** 获取编辑器内容 */
const getEditorContent = () => {
  if (fapi.value) {
    const formData = fapi.value.formData()
    const editorField = Object.keys(formData)[0]
    return formData[editorField] || '<p>合同内容</p>'
  }
  return '<p>合同内容</p>'
}

/** 清理HTML标签 */
const cleanHtml = (html: string) => {
  const div = document.createElement('div')
  div.innerHTML = html
  return div.textContent || div.innerText || ''
}

/** 设置编辑器内容 */
const setEditorContent = (content: string) => {
  if (fapi.value) {
    const editorField = Object.keys(fapi.value.formData())[0]
    fapi.value.setValue(editorField, content)
  }
}

/** 处理Markdown文件导入 */
const handleFileChange = (file: File) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const markdown = e.target?.result as string
      // 将Markdown转换为HTML
      const html = marked(markdown)
      // 设置到编辑器
      setEditorContent(html)
      ElMessage.success('Markdown导入成功')
    } catch (error) {
      console.error('Markdown导入失败:', error)
      ElMessage.error('Markdown导入失败')
    }
  }
  reader.readAsText(file.raw)
}

/** 复制内容到剪贴板 */
const copyContent = async () => {
  try {
    const content = getEditorContent()
    
    // 创建一个临时的div元素来保存HTML内容
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = content
    
    // 选择临时div
    document.body.appendChild(tempDiv)
    const range = document.createRange()
    range.selectNode(tempDiv)
    const selection = window.getSelection()
    selection?.removeAllRanges()
    selection?.addRange(range)
    
    // 执行复制命令
    document.execCommand('copy')
    
    // 清理
    selection?.removeAllRanges()
    document.body.removeChild(tempDiv)
    
    ElMessage.success('内容已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

/** 导出Markdown */
const exportMarkdown = () => {
  try {
    const html = getEditorContent()
    // 将HTML转换为Markdown
    const markdown = turndownService.turndown(html)
    
    // 创建并下载文件
    const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' })
    saveAs(blob, `${contractName.value}.md`)
    
    ElMessage.success('Markdown导出成功')
  } catch (error) {
    console.error('Markdown导出失败:', error)
    ElMessage.error('Markdown导出失败')
  }
}

/** 导出Word文档 (保留格式) */
const exportWord = () => {
  try {
    const content = getEditorContent()
    
    // 创建一个完整的HTML文档
    const htmlContent = `
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="UTF-8">
          <title>${contractName.value}</title>
          <style>
            body {
              font-family: Arial, sans-serif;
              font-size: 12pt;
              line-height: 1.5;
              margin: 2cm;
            }
            table {
              border-collapse: collapse;
              width: 100%;
            }
            table, th, td {
              border: 1px solid black;
              padding: 8px;
            }
            th {
              background-color: #f2f2f2;
            }
          </style>
        </head>
        <body>
          ${content}
        </body>
      </html>
    `
    
    // 创建一个Blob对象
    const blob = new Blob([htmlContent], { type: 'application/msword' })
    
    // 使用file-saver保存文件
    saveAs(blob, `${contractName.value}.doc`)
    
    ElMessage.success('Word文档导出成功 (请在Word中打开)')
  } catch (error) {
    console.error('导出Word文档失败:', error)
    ElMessage.error('导出Word文档失败')
  }
}

/** 导出PDF文档 */
const exportPDF = () => {
  try {
    const content = getEditorContent()
    
    // 创建临时DOM元素
    const element = document.createElement('div')
    element.innerHTML = content
    document.body.appendChild(element)
    
    // 配置PDF导出选项
    const opt = {
      margin: 1,
      filename: `${contractName.value}.pdf`,
      image: { type: 'jpeg', quality: 0.98 },
      html2canvas: { scale: 2 },
      jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
    }
    
    // 导出PDF
    html2pdf().from(element).set(opt).save().then(() => {
      document.body.removeChild(element)
      ElMessage.success('PDF文档导出成功')
    })
  } catch (error) {
    console.error('导出PDF文档失败:', error)
    ElMessage.error('导出PDF文档失败')
  }
}

// 初始化 turndown 用于将 HTML 转换为 Markdown
const turndownService = new TurndownService({
  headingStyle: 'atx',
  codeBlockStyle: 'fenced'
})

defineExpose({ open })
</script>

<style scoped>
.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: center;
}

:deep(.upload-demo) {
  display: inline-block;
}
</style>